/*
 * @Descripttion: your project
 * @version: 1.0
 * @Author: hongweixun
 * @Date: 2022-07-12 09:27:40
 * @LastEditors: hongweixun
 * @LastEditTime: 2022-07-23 09:19:10
 */
import store from '../store'
var websock = null
var globalCallback = null
var socketUrl = window.location.hostname
// var socketUrl = 'campus.hlzhjy.com:50080'
// 初始化websocket
function initWebSocket () {
  // ws地址 -->这里是你的请求路径
  var ws = `ws://${socketUrl}/WS/`
  console.log(ws)
  if (window.WebSocket) {
    websock = new WebSocket(ws)
    websock.onmessage = function (e) {
      websocketonmessage(e)
    }
    websock.onclose = function (e) {
      websocketclose(e)
    }
    websock.onopen = function () {
      websocketOpen()
    }

    // 连接发生错误的回调方法
    websock.onerror = function () {
      setTimeout(function () {
        initWebSocket()
      }, 2000)
      console.log('WebSocket连接发生错误')
    }
  } else {
    console.log('您当前的浏览器不支持websocket,推荐使用火狐或者谷歌浏览器')
  }
}

// 实际调用的方法
function sendSock (agentData, callback) {
  // console.log(typeof callback)
  globalCallback = callback
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback)
    }, 1000)
  } else {
    // 若未开启 ，则等待2s后重新调用
    setTimeout(function () {
      initWebSocket()
      sendSock(agentData, callback)
    }, 2000)
  }
}

// 数据接收
function websocketonmessage (e) {
  // console.log(typeof globalCallback)
  // console.log((e))
  globalCallback(JSON.parse(e.data))
}

// 数据发送
function websocketsend (agentData) {
  // console.log('jsonstr=' + JSON.stringify(agentData))
  if (agentData !== '' && agentData !== null) {
    websock.send('jsonstr=' + JSON.stringify(agentData))
  }
}

// 关闭
function websocketclose (e) {
  store.state.websocketErr = true
  setTimeout(function () {
    initWebSocket()
  }, 2000)
  console.log('connection closed')
}

// 创建 websocket 连接
function websocketOpen (e) {
  window.sessionStorage.setItem('socket', 1)
  store.state.websocketErr = false
  console.log('连接成功')
}

// initWebSocket()

// 将方法暴露出去
export {
  sendSock,
  initWebSocket,
  websocketclose
}
